package cn.yunyichina.provider.message.alipay.service;



import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.HospitalPlatformRelate;
import cn.yunyichina.provider.iface.entity.MsgLog;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.message.alipay.entity.ImageMessage;
import cn.yunyichina.provider.message.alipay.entity.MsgTemplateContent;
import cn.yunyichina.provider.message.alipay.utils.AlipayMessageSendUtils;
import cn.yunyichina.utils.convert.JsonUtils;

/**
* 挂号服务子系统dubbo入口
* @author adriftor
* @date 2016-07-29
*
*/
@Service("alipaymessageServiceImpl")
public class AlipayMessageServiceImpl {
	
	private static Logger logger = LoggerFactory.getLogger(AlipayMessageServiceImpl.class);
	/**
	 * 获取医院和平台的消息配置关系
	 * @param hospitalCode
	 * @return
	 */
	private static HospitalPlatformRelate getMessagePlatform(String hospitalCode) {
		try {
			JSONObject param = new JSONObject();
			param.put("hospital_code", hospitalCode);
			param.put("platform_code", "alipay");
			HospitalPlatformRelate  hospitalPlatformRelate = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.hospital.message.platform.get", JsonUtils.toJsonString(param)).getResult(),HospitalPlatformRelate.class);
			logger.debug("yyt.base.hospital.message.platform.get返回："+JsonUtils.toJsonString(hospitalPlatformRelate));
			return hospitalPlatformRelate;
		} catch (Exception e) {
			logger.error("获取父级平台异常,hospitalCode="+hospitalCode);
			logger.error(e.toString());
			throw new CallException("9002", "messagePlatform",e);
		}

	}
	
	/**
	 * 发送纯文字信息
	 * yyt.alipay.alipaymessage.text.send
	 * @param toUser 接收人ID
	 * @param msgContent 内容
	 * @param hospitalCode
	 * */
	public void sendAlipayMessageText(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
		
		AlipayMessageSendUtils.sendTextMessage(param.getString("to_user"), param.getString("org_app_code"), param.getString("msg_content"),param.getShortValue("platform_type"),paymentSettingResponse.getPayAppId(),paymentSettingResponse.getPrivateKey(),JsonUtils.toJsonString(param.get("sms_msg_content")));
		
//		HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("org_code"));
//		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
//			AlipayMessageSendUtils.sendTextMessage(param.getString("to_user"),param.getString("org_app_code"),  hospitalPlatformRelate.getPlatformHospitalCode(),param.getString("msg_content"),param.getShortValue("platform_type"));
//		}
	}
	
	/**
	 * 发送单图文消息
	 * yyt.alipay.alipaymessage.image.send
	 * @param toUser 接收人ID
	 * @param org_app_code
	 * @param org_code
	 * @param desc 备注
	 * @param img_src 图片地址
	 * @param title 标题
	 * @param url 点击图片后转向的url
	 * @param actionName 链接文字
	 * */
	public void sendAlipayMessageImage(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		ImageMessage imageMessage = JsonUtils.parseObject(strJson,ImageMessage.class);
		
		PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
		
		AlipayMessageSendUtils.sendSingleImageMessage(param.getString("to_user"),  imageMessage,paymentSettingResponse.getPayAppId(),paymentSettingResponse.getPrivateKey());
		
	}
	
	/**
	 * 发送多图文信息
	 * yyt.alipay.alipaymessage.images.send
	 * @param toUser 接收人ID
	 * @param hospitalCode
	 * @param list_image_message List<ImageMessage>数组对象：[{desc:"描述",imageUrl:"要显示的图片的SRC",title:"消息标题",url:"点击图片后转向的URL",action_name:"图片提示语,如 立即查看"}]
	 * */
	public void sendAlipayMessageImages(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		List<ImageMessage> listImageMessage = JsonUtils.parseArray(param.getString("list_image_message"),ImageMessage.class);
		AlipayMessageSendUtils.sendMultiImageMessage(param.getString("to_user"), param.getString("hospital_code"), listImageMessage);
		
		HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
			AlipayMessageSendUtils.sendMultiImageMessage(param.getString("to_user"), hospitalPlatformRelate.getPlatformHospitalCode(), listImageMessage);
		}
	}


	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		AlipayMessageServiceImpl service = context.getBean(AlipayMessageServiceImpl.class);
		service.sendAlipayMessageTemplate("{\"payment_setting\":{\"pay_app_id\":\"2016030701192208\",\"org_id\":\"ffdbc274acbd11e6990400163e0042e9\",\"org_name\":\"中山大学附属第八医院\",\"org_code\":\"zsdxfsdbyy\",\"merchant_account\":\"88315036@qq.com\",\"secret_key\":\"1YBIDzuZY3ITJY2175Njkw==\",\"pay_public_key\":\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlmzApRkPmCtQx8g8Lb+hRRm6usUu7TDFuGqIQHbIILlKI8e0jkjNh1B2qlLmWbZRPeGRMoYBWap5Yc20uZ8bTEf7LnRGGP+E/C3J1lCGWeK1JGNQXjAmKzIZcRSQ5Vobm7BAlgkRx1xn3mm9VNXBYKyzWXuPsMNJRCs3Wpxa17QXUYG/QG7hLDHTyjQnnxk58QOgCSjAUNk/rlHEPfIl/YlICe7idZPojr3S2pgRC/Na4uTuwxlkCXd7wRmWYwWlUX6MqsDpU0+/7S8jre8NLg6UwqPQBQ19sRLp6mDh4wp9lHvZBfvdXyHg1DbbFq0lEfAmpMQ7NttkxuJQhaMjgQIDAQAB\",\"public_key\":\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlmzApRkPmCtQx8g8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mtIeoAk6nAQKBgQDFa/1ysFHHQpT1+hEH0a165CQkenBGFahC/BFyVK9evj4CuXiaklzV6BysnYqwqLLHNLgXLrmrRaJJNtCARRYV6R5RykEY+rFSZiMZyzS/OAEepsCvfLnffccI3M/4Y0t6th9GxHLaCcpQZDQj8AZKyxVtbtX5smu6tOTT5lETOwKBgQDAkD5iK+unXgZSqDtDmOevxVvFwnAHmRpGrtkbFVmPjHt1K15lz+hLPWRpOLv4I2V+yNLvYn0aeTnlYGIJPBWVHDukokeNMJdoU46+klfV/RjjPPXEiLDhky1Y0KUTMD7Ze2RRZ2HUD96enCxDKOinBgMSGSaLB/jZm8amkOftQQKBgCIRIXoh/Oqijavoi/nKb+It7iKxUiB16kQs1SHihSSXNYIo2SvrJ8Ptusz6no0ff0Iq0b2GXZm1eWyi3dXUlhwPzyCUAym5UNIEN/hifWal1mOgqM1fe3+aZ7cay3R0RfkV5k3C5oLDf7rhn7G34I4Vf0wT/S6KYFamknoSW1kzAoGAIuE924x3GA7o+EnuyjTFKsqF8BFjN40c/FapjsVUPrNEnZmodKqvOgm5yXF0YuMOfGOmCaR+YrA4s3q8501R33uIti6K5WE627Pe9FgPvvwkaOze26Wi3IlLOn44mHwxtjUqm7AtQTtKqNJDFjsvwSlOnxWdLKvaAJi95+fxisECgYEApjCkCsiWuvmjHgDHyP7T2RUMGpL7+OhLnPdjPRH2Jom2qiIbLiQ2qgx/3nBFFqDk7aUbG/s74HBpo2P689TEy62UEvgoB0oBU0MZ9ZWrj4vd7TPp6psFYkn9qozFDyrMmRjOKgalINpArgNgWw1GRPzm4/cx0hM55SRC5/xVUFw=\",\"partner_id\":\"2088221353189095\",\"pay_mode\":22,\"check_flag\":1,\"enable_flag\":1},\"platform_type\":2,\"template_id\":\"b39b33f1df934230a2e9c47aa9003bb4\",\"org_code\":\"szsdsrmyy\",\"list_msg_template_content\":\"[{\\\"node\\\":\\\"first\\\",\\\"value\\\":\\\"您好，您预约的医生有变更\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"keyword1\\\",\\\"value\\\":\\\"李嘉亮\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"keyword2\\\",\\\"value\\\":\\\"深圳市第三人民医院\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"keyword3\\\",\\\"value\\\":\\\"王萍\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"keyword4\\\",\\\"value\\\":\\\"刘智\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"keyword5\\\",\\\"value\\\":\\\"2018-02-28 16:30-17:00\\\",\\\"font_color\\\":\\\"black\\\"},{\\\"node\\\":\\\"remark\\\",\\\"value\\\":\\\"请留意医生变更情况就诊\\\",\\\"font_color\\\":\\\"black\\\"}]\",\"to_user\":\"2088302648586442\",\"org_app_code\":\"yyt48fe49dbe6eb1cee\",\"head_color\":\"black\",\"url\":\"http://webtest.yunyichina.cn/platform/dist/pages/register/index.html#/regDetail?order_no=YRP201802271112521834&app_code=yyt48fe49dbe6eb1cee&open_id=2088302648586442&app_id=2015102000489434\"}" , "");
	}

	
	/**
	 * 推送模版消息
	 * yyt.alipay.alipaymessage.template.send
	 * @param toUser  接收人ID
	 * @param hospitalCode 
	 * @param headColor  标题栏颜色
	 * @param url 点击后转向的URL
	 * @param templateId 模板ID 
	 * @param list_msg_template_content List<MsgTemplateContent>数组对象，[{value:"显示的文本信息",node:"变量名",font_color:"字体颜色"}]
	 * @return
	 */
	public void sendAlipayMessageTemplate(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		String smsMsgContent = JsonUtils.toJsonString(param.get("sms_msg_content"));
		//直接把要发送的模板消息放入队列里
//		AlipayMessageSendUtils.addMessageToMq(strJson);
				
		List<MsgTemplateContent> listMsgTemplateContent = JsonUtils.parseArray(JsonUtils.toJsonString(param.getJSONArray("list_msg_template_content")),MsgTemplateContent.class);
		//根据orgAppCode发送模板消息
		if (param.containsKey("org_app_code") && StringUtils.isNotBlank(param.getString("org_app_code"))) {
			
			String orgCode = param.containsKey("org_code") ? param.getString("org_code") : "";
			PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
			
			AlipayMessageSendUtils.sendTemlateMessageByAppCode(param.getString("to_user"), param.getString("org_app_code"),orgCode,
					param.getString("template_id"), 
					listMsgTemplateContent, 
					param.getString("url"), 
					param.getString("head_color"),param.getShort("platform_type"),paymentSettingResponse.getPayAppId(),
					paymentSettingResponse.getPrivateKey(),paymentSettingResponse.getPayPublicKey(),smsMsgContent);
		}
		else {
			AlipayMessageSendUtils.sendTemlateMessage(param.getString("to_user"), param.getString("hospital_code"),
					param.getString("template_id"), 
					listMsgTemplateContent, 
					param.getString("url"), 
					param.getString("head_color"),smsMsgContent);
			
			HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
			if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
				AlipayMessageSendUtils.sendTemlateMessage(param.getString("to_user"), hospitalPlatformRelate.getPlatformHospitalCode(),
						param.getString("template_id"), 
						listMsgTemplateContent, 
						param.getString("url"), 
						param.getString("head_color"),smsMsgContent);
			}
			
		}
		
	}
	
	/**
	 * 发送医疗挂号通知
	 * yyt.alipay.alipaymessage.reg.notify.send
	 * @param strJson
	 * @param sessionId
	 */
	public void sendAlipayMessageRegNotify(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
			
		
		PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
		
		AlipayMessageSendUtils.sendRegNotify(strJson,paymentSettingResponse.getPayAppId(),paymentSettingResponse.getPrivateKey());
	
	}
	
	/**
	 * 群体发送文本消息
	 * yyt.alipay.alipaymessage.text.by.group.send
	 * @param hospitalCode
	 * @param text
	 */
    public void sendAlipayMessageTextByGroup(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		AlipayMessageSendUtils.sendGroupTextMessage( param.getString("hospital_code"),param.getString("text"));
		
		HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
			AlipayMessageSendUtils.sendGroupTextMessage(hospitalPlatformRelate.getPlatformHospitalCode(),param.getString("text"));
		}
	}
    /**
     * 群体发送图文消息
     * yyt.alipay.alipaymessage.image.by.group.send
     * @param hospitalCode
     * @param desc 备注
	 * @param img_src 图片地址
	 * @param title 标题
	 * @param url 点击图片后转向的url
     */
    public void sendAlipayMessageImageByGroup(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		ImageMessage imageMessage = JsonUtils.parseObject(strJson,ImageMessage.class);
		AlipayMessageSendUtils.sendGroupImageMessage( param.getString("hospital_code"),imageMessage);
		
		HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
			AlipayMessageSendUtils.sendGroupImageMessage( hospitalPlatformRelate.getPlatformHospitalCode(),imageMessage);
		}
	}
    
    /**
	 * 匹配推送 精准推送
	 * yyt.alipay.alipaymessage.template.by.mobile.send 
	 * @param hospitalCode
	 * @param mobile 手机号码
	 * @param templateId 支付宝模板ID
	 * @return
	 */
	public void sendAlipayMessageTemplateByMobile(String strJson,String sessionId) {
		JSONObject param = JsonUtils.parseObject(strJson);
		AlipayMessageSendUtils.sendAlipayMessageTemplateByMoble(param.getString("hospital_code"),param.getString("mobile"),param.getString("template_id"));
		
		HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
			AlipayMessageSendUtils.sendAlipayMessageTemplateByMoble(hospitalPlatformRelate.getPlatformHospitalCode(),param.getString("mobile"),param.getString("template_id"));
			
		}
	}
	
	/**
	 * 保存发送日志接口
	 * yyt.alipay.alipaymessage.msg.log.save
	 * @param strJson MsgLog对象
	 * @param sessionId
	 */
	public void saveAlipayMessageMsgLog(String strJson,String sessionId) {
		MsgLog msgLog = JsonUtils.parseObject(strJson,MsgLog.class);
		AlipayMessageSendUtils.saveMsgLog(msgLog);
		
	}
}
